package bmaso.purest;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MimeTypePattern {
	private String type;
	private String subtype;
	
	private static Pattern mimeTypePattern =
		Pattern.compile("^([^/]+)/([^;]+)(;\\s*[^;]+)?$");
	
	public MimeTypePattern(String pattern) throws IllegalMIMETypePattern {
		Matcher m = mimeTypePattern.matcher(pattern);
		if(!m.matches()) {
			throw new IllegalMIMETypePattern(pattern);
		}
		
		type = m.group(1);
		if("*".equals(type)) {
			type = null;
		}
		
		subtype = m.group(2);
		if("*".equals(subtype)) {
			subtype = null;
		}
	}
	
	public boolean matches(String mimeType) {
		if(matchesAll()) {
			return true;
		}
		
		Matcher m = mimeTypePattern.matcher(mimeType);
		if(!m.matches()) {
			//...that's odd...
			return false;
		}
		
		if(type != null) {
			if(!type.equals(m.group(1))) {
				return false;
			}
		}
		
		if(subtype != null) {
			if(!subtype.equals(m.group(2))) {
				return false;
			}
		}
		
		return true;
	}
	
	public boolean matchesAll() {
		return type == null && subtype == null;
	}
	
	public String getType() {
		return type;
	}
	
	public String getSubtype() {
		return subtype;
	}
}
